import React,{useEffect, useState} from "react";
import Note from "./Note";
import Editor from "./Editor";
import {db,loadCollection} from '../database'

const Notes = ()=>{

    const [notes,setNotes]=useState([
        // {body:'hello'},
        // {body:'你好~'}
    ])
    const destroyEntity=(entity)=>{
        // console.log(entity);
        // 不是这一项的就留下
        // setState
        const _entities=notes.filter(
            item=>item.$loki!==entity.$loki
        )
        // console.log(_entities)
        setNotes(_entities)
        // 删除同步数据库
        loadCollection('notes')
            .then((collection)=>{
                collection.remove(entity)
                db.saveDatabase()
            })
        
    }
    const noteItems=notes.map(
        // (note,index) => <li key={index}>{note.body}</li>
        (note,index)=>
        <Note 
            key={note.$loki}
            entity={note}
            destroyEntity={destroyEntity}/>

    )
    
    const createEntity=()=>{

    }

    //先把页面模板显示出来 静态部分先显示出来
    // JSX->babel + html/css 渲染 要花时间 组件挂载及渲染时间
    // 再从数据库里取出来 也要花时间 但无法保证谁先执行完 useEffect DomContentLoaded
    // 再setNotes 页面响应
    const getInitialData=()=>{
        loadCollection('notes')
            .then((collection)=>{
                // console.log(collection)
                // collection.insert([
                //     {body:'hello'},
                //     {body:'你好~'}
                // ])
                const entities=collection.chain()
                    .find()     //select * from orderby
                    .simplesort('$loki','isdesc')
                    .data()
                console.log(entities)
                setNotes(entities)
            })
    }
    useEffect(()=>{
        // 组件挂载后执行 生命周期
        // console.log('----');
        getInitialData()
    },[])
    // console.log('|||||||')
    return (
        <div className="ui container notes">
            <h4 className="ui horizontal divider header">
                <i className="paw icon" />
                Notes App _React.js
            </h4>
            <button onClick={createEntity} 
                    className="ui right floated basic violte button">
                添加笔记
            </button>
            <div className="ui divided items">
                {noteItems}
            </div>
            {/* <Note /> */}
            {/* <Editor updateEntity={updateEntity}/> */}
        </div>
    )
}

export default Notes